package com.emenu.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

public class SaveMenuImg {

	/**
	 * @param bitName
	 *            图片名字
	 * @param path
	 *            数据库图片地址
	 * 
	 * @param version
	 *            版本
	 * @param mBitmap
	 *            服务器返回字符串
	 * @throws IOException
	 */
	public static void saveMyBitmap(String bitName, String path,
			String version, String imgstr) throws IOException {
		String SDPATH = Environment.getExternalStorageDirectory()
				+ File.separator + "Picture" + File.separator;

		File destDir = new File(SDPATH + getpath(path));
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		File f = new File(SDPATH + getpath(path) + bitName + ".jpg");
		if (!f.exists()) {
			f.createNewFile();
			
		} else {
			f.delete();
			f.createNewFile();
		}

		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		Bitmap mBitmap = getBitmap(imgstr);
		mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
		
		//回收图片内存
		if (!mBitmap.isRecycled()) {
			mBitmap.recycle();
		}
		
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param base64str
	 *            ,服务器返回字符串
	 * @return
	 */
	public static Bitmap getBitmap(String base64str) {
		try {
			if (base64str.length() > 1) {
				byte[] bitmapArray;
				bitmapArray = Base64.decode(base64str, 0);
				return BitmapFactory.decodeByteArray(bitmapArray, 0,
						bitmapArray.length);
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * window路径转化linux路径,保存图片到sd卡
	 * 
	 * @param path
	 *            "2\水煮草鱼.jpg"得到 "2/"
	 * @return
	 */
	public static String getpath(String path) {
		String strs = "";
		if (path!=null && path.length() > 0) {

			int i = path.lastIndexOf("\\");
			strs = path.substring(0, i + 1).replaceAll("\\\\", "/");

		}else{
			return "";
		}
		return strs;
	}
	/**
	 * window路径转化linux路径,保存图片到sd卡
	 * 
	 * @param path
	 *            "2\水煮草鱼.jpg"得到 "2/水煮草鱼.jpg"
	 * @return
	 */
	public static String getpathName(String path) {
		String strs = "";
		if (path.length() > 0) {

			int i = path.lastIndexOf("\\");
			strs = path.replaceAll("\\\\", "/");

		}
		return strs;
	}
}
